package com.mmall.service.impl;

import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.common.TokenCache;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
import com.mmall.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;


/**
 * Create by lisy on Qingdao
 **/
@Service("iUserService")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ServerResponse<User> loginService(String username, String password){
        int checkResult = userMapper.checkUsername(username);
        if(checkResult == 0){
            //当前用户名不存在
            return ServerResponse.createByErrorMssage("用户名不存在");
        }
        //密码登录MD5
        String md5Password = MD5Util.MD5EncodeUtf8(password);

        User user = userMapper.userLogin(username, md5Password);
        if(user == null){
            return ServerResponse.createByErrorMssage("密码错误");
        }

        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess("登录成功", user);
    }

    @Override
    public ServerResponse<String> registerService(User user) {
        ServerResponse response = this.checkValid(user.getUsername(), Const.USERNAME);
        if(!response.isSuccess()){
            return response;
        }
        response = this.checkValid(user.getEmail(), Const.EMAIL);
        if(!response.isSuccess()){
            return response;
        }
        //密码使用MD5加密
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        int resultCount = userMapper.insert(user);
        if(resultCount == 0) {
            return ServerResponse.createByErrorMssage("用户注册失败");
        }
        return ServerResponse.createBySuccessMessage("用户注册成功");
    }

    //验证type类型的字段在数据库中有没有
    public ServerResponse<String> checkValid(String str, String type){
        if(StringUtils.isNotBlank(type)){
            if(Const.USERNAME.equals(type)){
                int resultCount = userMapper.checkUsername(str);
                if(resultCount > 0){
                    return ServerResponse.createByErrorMssage("checkValid用户名已经存在");
                }
            }
            if(Const.EMAIL.equals(type)){
                int resultCount = userMapper.checkEmail(str);
                if(resultCount > 0){
                    return ServerResponse.createByErrorMssage("checkValid电子邮件已经存在");
                }
            }
        }else {
            return ServerResponse.createByErrorMssage("checkValid中类型错误");
        }
        return ServerResponse.createBySuccessMessage("checkValid验证成功");
    }

    //取密码提示问题
    public ServerResponse<String> getQuestionByUsername(String username){
        ServerResponse response = this.checkValid(username, Const.USERNAME);
        if(response.isSuccess()){
            //用户不存在
            return ServerResponse.createByErrorMssage("取密码提示问题的时候，用户名不存在");
        }
        String question = userMapper.selectQuestionByUsername(username);
        if(StringUtils.isNotBlank(question)){
            return ServerResponse.createBySuccess("取密码提示问题成功", question);
        }
        return ServerResponse.createByErrorMssage("没取到密码提示问题");
    }

    //提交问题答案
    public ServerResponse<String> checkAswer(String username, String question, String answer){
        int resultCount = userMapper.checkAnswer(username, question, answer);
        if(resultCount == 0){
            //问题和答案不符合要求
            return ServerResponse.createByErrorMssage("验证问题答案失败");
        }
        String forgetToken = UUID.randomUUID().toString();
        TokenCache.setKey(TokenCache.TOKEN_PREFIX + username, forgetToken);
        return ServerResponse.createBySuccess(forgetToken);
    }

    //根据密码提示问题修改密码
    public ServerResponse<String> forgetResetPassword(String username, String passwordNew, String forgetToken){
        //先验证token
        if(StringUtils.isBlank(forgetToken)){
            return ServerResponse.createByErrorMssage("token为空，需要传递token");
        }
        //校验用户
        ServerResponse response = this.checkValid(username, Const.USERNAME);
        if(response.isSuccess()){
            //当前用户名不存在
            return response;
        }

        String userToken = TokenCache.getKey(TokenCache.TOKEN_PREFIX + username);
        if(StringUtils.isBlank(userToken)){
            return ServerResponse.createByErrorMssage("token为空，没取到");
        }
        if(!userToken.equals(forgetToken)){
            return ServerResponse.createByErrorMssage("token不相等啊！！重新验证用户名和密码提示问题");
        }
        String md5PasswordNew = MD5Util.MD5EncodeUtf8(passwordNew);
        int resultCount = userMapper.forgetResetPassword(username, md5PasswordNew);
        if(resultCount == 0){
            return ServerResponse.createByErrorMssage("修改密码失败了");
        }
        return ServerResponse.createBySuccessMessage("修改密码成功");
    }

    //登录状态下修改密码
    public ServerResponse<String> resetPassword(String passwordOld, String passwordNew, User user){
        //先检验旧密码是否一致
        int resultCount = userMapper.checkPassword(user.getId(), MD5Util.MD5EncodeUtf8(passwordOld));
        if(resultCount == 0){
            //旧密码输入错误
            return ServerResponse.createByErrorMssage("旧密码输入错误");
        }
        String md5PasswordNew = MD5Util.MD5EncodeUtf8(passwordNew);
        user.setPassword(md5PasswordNew);
        int updateResult = userMapper.updateByPrimaryKeySelective(user);
        if(updateResult == 0){
            return ServerResponse.createByErrorMssage("密码修改失败");
        }
        return ServerResponse.createBySuccessMessage("密码修改成功");
    }

    //修改用户信息
    public ServerResponse<User> updateInformation(User user){
        //验证email
        int resultCount = userMapper.checkEmailByUserId(user.getId(), user.getEmail());
        if(resultCount > 0){
            return ServerResponse.createByErrorMssage("email已经存在了，需要填写新的email地址");
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setAnswer(user.getAnswer());
        updateUser.setQuestion(user.getQuestion());

        int updateCount = userMapper.updateByPrimaryKeySelective(updateUser);
        if(updateCount > 0){
            return ServerResponse.createBySuccess("更新成功", updateUser);

        }
        return ServerResponse.createByErrorMssage("更新失败");
    }

    //获得用户信息
    public ServerResponse<User> getInformation(int userId){
        User user = userMapper.selectByPrimaryKey(userId);
        if(user == null){
            return ServerResponse.createByErrorMssage("找不到当前用户");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess("查找用户成功，并将密码初始化", user);
    }

    //判断是否为管理员
    public ServerResponse<String> checkUserRole(User user){
        if(user != null && user.getRole() == Const.Role.ROLE_ADMIN){
            return ServerResponse.createBySuccessMessage("用户为管理员，成功登录！");
        }
        return ServerResponse.createByError();
    }
}
